# encoding=utf-8
from storages.cache import cache
from constant.const import const
from concurrent.futures import ThreadPoolExecutor as tpe
import threading
import time

c = cache()
r = c.cache


# for i in range(100):
#     r.lpush(const.book_cache, str(i + 1))
def test1():
    with open("lua/lua_test1.lua", "r", encoding = "utf-8") as f:
        script = f.read()
    load = r.script_load(script)
    evalsha = r.evalsha(load, 1, "test_key", "test_value")
    print(evalsha)


def test2(local_key):
    while True:
        with open("lua/lock.lua", "r", encoding = "utf-8") as f:
            script = f.read()
        with open("lua/unlock.lua", "r", encoding = "utf-8") as f:
            unlock_script = f.read()
        load = r.script_load(script)
        is_lock = r.evalsha(load, 1, const.book_cache, local_key)
        if is_lock == 1:
            get = str(r.get(local_key), encoding = 'utf-8')
            try:
                print(get + " - " + local_key)
                print(f"Thread name: {threading.current_thread().name}")
            finally:
                unlock = r.script_load(unlock_script)
                r.evalsha(unlock, 1, local_key, get)
                time.sleep(5)
                print(f"Thread name: {threading.current_thread().name} time.sleep(5)")
                break
        # elif is_lock == 0:
        #     unlock = r.script_load(unlock_script)
        #     r.evalsha(unlock, 1, local_key, r.get(local_key))
        else:
            # 等待一段时间后再次尝试获取锁
            print(f"Thread {threading.current_thread().name} failed to acquire lock. Sleeping for 1 second.")
            time.sleep(1)


def main():
    with tpe(max_workers = 10) as p:
        for i in range(100):
            local_key = str(i + 1)
            p.submit(test2, local_key)


# 返回1就说明锁着了 ,0就是还没锁着
def lock(id):
    load = """
        local key = KEYS[1]
        local local_key = ARGV[1]
        if redis.call("exists", local_key) == 0 then
            redis.call("set", local_key, 1)
            return 1
        else
            return 0
        end
    """
    is_lock = r.eval(load, 1, const.book_cache, id)
    return is_lock
    # if is_lock == 1:
    #     print("ok")


# 返回1就说明删除锁 ,0就是还没删除锁
def unlock(id):
    unlock = """
        local key = KEYS[1]
        local value = ARGV[1]
        if redis.call("get", key) == value then
            redis.call("del", key)
            return 1
        else
            return 0
        end
    """
    get = str(r.get(id), encoding = 'utf-8')
    r.eval(unlock, 1, id, get)

# if __name__ == "__main__":
#     main()
